package com.lw.lost.activity

import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.view.Menu
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.lw.lost.R
import com.lw.lost.databinding.ActivityUserDetailBinding
import com.lw.lost.db.DBlost
import com.lw.lost.utils.PreferenceUtils

class UserDetailActivity : AppCompatActivity() {

    private lateinit var binding: ActivityUserDetailBinding
    private lateinit var db: DBlost
    private var userId: Long = -1
    private var currentUserId: Long = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityUserDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)
        supportActionBar?.apply {
            setDisplayHomeAsUpEnabled(true)
            title = "用户详情"
            setHomeAsUpIndicator(R.drawable.ic_back) // 使用白色的返回箭头
        }
        
        db = DBlost(this)
        currentUserId = PreferenceUtils.getUserId(this)
        userId = intent.getLongExtra("userId", -1)
        
        if (userId == -1L || userId == currentUserId) {
            finish()
            return
        }

        loadUserInfo()
        setupActionButton()
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.user_detail_menu, menu)
        // 设置所有菜单项的图标为白色
        for (i in 0 until menu.size()) {
            val item = menu.getItem(i)
            item.icon?.setTint(getColor(android.R.color.white))
        }
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_report -> {
                showReportDialog()
                true
            }
            R.id.action_delete_friend -> {
                showDeleteFriendDialog()
                true
            }
            android.R.id.home -> {
                finish()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun showReportDialog() {
        val reasons = arrayOf("垃圾信息", "色情内容", "暴力内容", "诈骗信息", "其他")
        var selectedReason = reasons[0]

        MaterialAlertDialogBuilder(this)
            .setTitle("举报用户")
            .setSingleChoiceItems(reasons, 0) { _, which ->
                selectedReason = reasons[which]
            }
            .setPositiveButton("确定") { _, _ ->
                submitReport(selectedReason)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun submitReport(reason: String) {
        val reportId = db.reportDao.insert(
            userId = currentUserId,
            targetId = userId,
            type = "user",
            reason = reason
        )

        if (reportId > 0) {
            Toast.makeText(this, "举报已提交", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "举报失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun showDeleteFriendDialog() {
        MaterialAlertDialogBuilder(this)
            .setTitle("删除好友")
            .setMessage("确定要删除该好友吗？删除后将无法恢复。")
            .setPositiveButton("确定") { _, _ ->
                deleteFriend()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun deleteFriend() {
        // 删除好友关系
        val result = db.matchRecordDao.deleteMatch(currentUserId, userId)
        // 删除聊天记录
        db.messageDao.deleteConversation(currentUserId, userId)

        if (result > 0) {
            Toast.makeText(this, "已删除好友", Toast.LENGTH_SHORT).show()
            finish()
        } else {
            Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun loadUserInfo() {
        val cursor = db.userDao.getUserById(userId)
        cursor.use { cursor ->
            if (cursor.moveToFirst()) {
                // 基本信息
                binding.tvName.text = cursor.getString(cursor.getColumnIndexOrThrow("name"))
                binding.tvGender.text = if (cursor.getInt(cursor.getColumnIndexOrThrow("gender")) == 0) "男" else "女"
                binding.tvAge.text = "${cursor.getInt(cursor.getColumnIndexOrThrow("age"))}岁"
                binding.tvPhone.text = cursor.getString(cursor.getColumnIndexOrThrow("phone"))

                // 加载头像
                val avatarPath = cursor.getString(cursor.getColumnIndexOrThrow("avatar"))
                if (!avatarPath.isNullOrEmpty()) {
                    Glide.with(this)
                        .load(avatarPath)
                        .circleCrop()
                        .placeholder(R.drawable.ic_avatar_default)
                        .error(R.drawable.ic_avatar_default)
                        .into(binding.ivAvatar)
                }
            }
        }

        // 加载兴趣信息
        val interestCursor = db.interestDao.getInterestsByUserId(userId)
        interestCursor.use { cursor ->
            if (cursor.moveToFirst()) {
                binding.tvEducation.text = cursor.getString(cursor.getColumnIndexOrThrow("education"))
                binding.tvInterests.text = cursor.getString(cursor.getColumnIndexOrThrow("content"))
            }
        }
    }

    private fun setupActionButton() {
        // 检查是否已经是好友
        val cursor = db.matchRecordDao.getMatchRecordsByUserId(currentUserId)
        var isFriend = false
        
        cursor.use { cursor ->
            while (cursor.moveToNext()) {
                val matchedUserId = if (cursor.getLong(cursor.getColumnIndexOrThrow("userId")) == currentUserId) {
                    cursor.getLong(cursor.getColumnIndexOrThrow("matchedUserId"))
                } else {
                    cursor.getLong(cursor.getColumnIndexOrThrow("userId"))
                }
                
                if (matchedUserId == userId) {
                    isFriend = true
                    break
                }
            }
        }

        // 根据好友状态设置按钮
        if (isFriend) {
            binding.btnAction.text = "发消息"
            binding.btnAction.setOnClickListener {
                startChat()
            }
        } else {
            binding.btnAction.text = "加为好友"
            binding.btnAction.setOnClickListener {
                addFriend()
            }
        }
    }

    private fun addFriend() {
        // 检查是否已经发送过请求
        if (db.friendRequestDao.hasUnhandledRequest(currentUserId, userId)) {
            Toast.makeText(this, "已发送���友请求，请等待对方处理", Toast.LENGTH_SHORT).show()
            return
        }

        // 显示发送好友请求对话框
        val dialogView = layoutInflater.inflate(R.layout.dialog_friend_request, null)
        val etMessage = dialogView.findViewById<EditText>(R.id.etMessage)

        AlertDialog.Builder(this)
            .setTitle("发送好友请求")
            .setView(dialogView)
            .setPositiveButton("发送") { _, _ ->
                val message = etMessage.text.toString().trim()
                if (message.isEmpty()) {
                    Toast.makeText(this, "请输入验证信息", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }

                // 发送好友请求
                val result = db.friendRequestDao.sendRequest(currentUserId, userId, message)
                if (result > 0) {
                    Toast.makeText(this, "好友请求已发送", Toast.LENGTH_SHORT).show()
                    binding.btnAction.isEnabled = false
                    binding.btnAction.text = "等待验证"
                } else {
                    Toast.makeText(this, "发送失败，请重试", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取���", null)
            .show()
    }

    private fun startChat() {
        val intent = Intent(this, ChatActivity::class.java)
        intent.putExtra("userId", userId)
        startActivity(intent)
    }
} 